<template>
  <div class="def-tree">
    <el-tree
      v-bind="$attrs"
      :lazy="lazy"
      :load="lazy && lazyOptions && loadNode"
      @current-change="handleNodeClick" />
  </div>
</template>

<script lang="ts" setup>
import type Node from 'element-plus/es/components/tree/src/model/node'
import { PropType, reactive } from 'vue'
import { ITreeLazyOptions } from '@/base-ui/tree/types'

const props = defineProps({
  // 是否开启懒加载
  lazy: {
    type: Boolean,
    default: false
  },
  // 懒加载配置
  lazyOptions: {
    type: Object as PropType<ITreeLazyOptions>,
    default: () => null
  }
})

const emits = defineEmits(['currentChange'])

// 树当前选中节点变化时触发的事件
const handleNodeClick = (data: any) => {
  emits('currentChange', data)
}
const lazyOpt = reactive<ITreeLazyOptions>(props.lazyOptions)
const loadNode = async (node: Node, resolve: (data: any) => void) => {
  // 处理第一层数据
  if (node.level === 0) {
    return resolve(await lazyOpt.fn())
  }
  // 处理层级
  if (lazyOpt.level) {
    if (node.level > lazyOpt.level) return resolve([])
  }
  // 处理内层数据
  setTimeout(async () => {
    const id = lazyOpt.id
    resolve(await lazyOpt.fn((node as any)[id]))
  }, lazyOpt.time || 500)
}
</script>

<style scoped lang="scss">
.def-tree {
}
</style>
